package com.interrobang.gui;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.interrobang.anime.Anime;
import com.interrobang.anime.AnimeList;
import com.interrobang.anime.ImageFilter;
import com.interrobang.anime.NameChecker;
import com.interrobang.anime.Rule;

public class AnimePanel extends JPanel 
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5395019373721381540L;
	private MainPanel panel;
	private Anime anime;
	private AnimeList aList;
	private JList list;
	private JButton add;
	private JButton remove;
	private ButtonListener listener;
	private JButton back;
	private final String FILENAME = "Data/data.haruhi";
	private JButton upload;
	private JFileChooser fc = new JFileChooser();
	private NameChecker check = new NameChecker();
	private JLabel title;
	private JLabel episode;
	private JScrollPane listPane;
	private ImagePanel image;
	
	public AnimePanel(Anime anime, MainPanel panel, AnimeList list)
	{
		this.anime = anime;
		aList = list;
		this.panel = panel;
		listener = new ButtonListener();
		update();				
	}
	
	public void update()
	{
		removeAll();						
		initComponents();
		updateUI();
		
	}
	
	private void initComponents() {

        listPane = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        add = new javax.swing.JButton();
        remove = new javax.swing.JButton();
        back = new javax.swing.JButton();
        upload = new javax.swing.JButton();
        title = new javax.swing.JLabel();
        episode = new javax.swing.JLabel();
        image = new com.interrobang.gui.ImagePanel();
        
        Image im;
		try {
			im = ImageIO.read(new File("Graphics/" + check.check(anime.getTitle()) + ".png"));
			 image.setImage(im);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
        
        String[] entries;
		entries = new String[anime.getRules().size()];
			for (int i = 0; i < entries.length; i++) 
			{
				entries[i] = anime.getRules().get(i).getRule();
			}

        list = new JList(entries);
        list.addListSelectionListener(listener);
        listPane.setViewportView(list);

        add.setFont(new java.awt.Font("Comic Sans MS", 0, 12)); // NOI18N
        add.setText("Add new Rule");
        add.addActionListener(listener);
        remove.setFont(new java.awt.Font("Comic Sans MS", 0, 12)); // NOI18N
        remove.setText("Remove Rule");
        remove.addActionListener(listener);
        back.setFont(new java.awt.Font("Comic Sans MS", 0, 12)); // NOI18N
        back.setText("Back");
        back.addActionListener(listener);
        upload.setFont(new java.awt.Font("Comic Sans MS", 0, 12)); // NOI18N
        upload.setText("Add a Picture");
        upload.addActionListener(listener);
        title.setFont(new java.awt.Font("Comic Sans MS", 0, 24)); // NOI18N
        title.setText(anime.getTitle());

        episode.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        episode.setText("Episode: " + String.valueOf(anime.getEpisodes()));

        javax.swing.GroupLayout imageLayout = new javax.swing.GroupLayout(image);
        image.setLayout(imageLayout);
        imageLayout.setHorizontalGroup(
            imageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 190, Short.MAX_VALUE)
        );
        imageLayout.setVerticalGroup(
            imageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 119, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addComponent(upload)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(title))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(episode))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(add)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(remove))
                        .addComponent(listPane, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(158, 158, 158)
                        .addComponent(back)))
                .addContainerGap(64, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(upload))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(title)
                        .addGap(18, 18, 18)
                        .addComponent(episode)
                        .addGap(29, 29, 29)
                        .addComponent(listPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(remove)
                            .addComponent(add))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(back)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }
	
	public void paintComponent (Graphics g) {
        super.paintComponent (g);
        image.paint(g);
    }

	
	private class ButtonListener implements ActionListener, ListSelectionListener
	{
		int index;
		@Override
		public void actionPerformed(ActionEvent event) 
		{
			
			
			if(event.getSource() == add)
			{
				String input = JOptionPane.showInputDialog("Enter a New Rule");
				if(input.length() == 0)
				{
					JOptionPane.showMessageDialog(panel, "Rules must contain atleast one character");
				}
				else
				{
					Rule rule = new Rule(input);
					anime.addRule(rule);
					update();
				}
			}
			if(event.getSource() ==  remove)
			{
				if(anime.getRules().size() == 0)
				{
					JOptionPane.showMessageDialog(panel, "There are no rules to remove");
				}
				else
				{
					int returnValue = JOptionPane.showConfirmDialog(panel, "Are you sure you want to remove this rule?");
					if(returnValue == JOptionPane.YES_OPTION)
					{
						anime.getRules().remove(index);
						update();
					}
				}
			}
			if(event.getSource() == back)
			{
				FileOutputStream fos = null;
				ObjectOutputStream out = null;
				try
				{
					fos = new FileOutputStream(FILENAME);
					out = new ObjectOutputStream(fos);
					out.writeObject(aList);
					out.close();
					}catch(IOException ex)
				    {
					       System.out.print("File not found");
					}
					panel.setAddActive(false);
					panel.setMenuActive(false);
					panel.setViewActive(true);
					panel.update();
				}
			if(event.getSource() == upload)
			{
				
				fc.setFileFilter(new ImageFilter());
				int returnVal = fc.showOpenDialog(panel);
				 if (returnVal == JFileChooser.APPROVE_OPTION) 
				 {
			            File file = fc.getSelectedFile();
			            try {
			            	BufferedImage bi = ImageIO.read(file); // retrieve image
			            	File outputfile = new File("Graphics/" + check.check(anime.getTitle()) + ".png");
			                if(bi == null)
			                	System.out.print("i is null");
			                ImageIO.write(bi, "png", outputfile);
			                update();
			                JOptionPane.showMessageDialog(panel, "The Image has been added");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				 }
				 else
				 {
					 
				 }
			}
			
		}

		@Override
		public void valueChanged(ListSelectionEvent event) 
		{
			if (!event.getValueIsAdjusting())
			{
				this.index = list.getSelectedIndex();
				
			}
		}
		
	}

}
